package com.yupi.yuaicodemother.config;

import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * 普通流式模型配置, 用于处理原生模式生成
 */
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "langchain4j.open-ai.streaming-chat-model")
@Data
public class StreamingChatModelConfig {

    private String baseUrl;

    private String apiKey;

    private String modelName;

    private Integer maxTokens;

    private Double temperature;

    private boolean logRequests;

    private boolean logResponses;

    private Duration timeout = Duration.ofSeconds(120);

    @Bean
    @Scope("prototype")
    public StreamingChatModel streamingChatModelPrototype() {
        // 参数校验
        if (!StringUtils.hasText(baseUrl)) {
            throw new IllegalStateException("streaming-chat-model.base-url 配置不能为空，请在 application.yml 中配置 langchain4j.open-ai.streaming-chat-model.base-url");
        }
        if (!StringUtils.hasText(apiKey)) {
            throw new IllegalStateException("streaming-chat-model.api-key 配置不能为空，请在 application.yml 中配置 langchain4j.open-ai.streaming-chat-model.api-key");
        }
        if (!StringUtils.hasText(modelName)) {
            throw new IllegalStateException("streaming-chat-model.model-name 配置不能为空，请在 application.yml 中配置 langchain4j.open-ai.streaming-chat-model.model-name");
        }

        log.info("初始化 StreamingChatModel: baseUrl={}, modelName={}, timeout={}s", 
                baseUrl, modelName, timeout.getSeconds());

        return OpenAiStreamingChatModel.builder()
                .apiKey(apiKey)
                .baseUrl(baseUrl)
                .modelName(modelName)
                .maxTokens(maxTokens)
                .temperature(temperature)
                .logRequests(logRequests)
                .logResponses(logResponses)
                .timeout(timeout)
                .build();
    }
}